<?php

/**
 * import local QR encoder
 */
Yii::import('application.extensions.phpqrcode.*');
require_once( dirname(__FILE__) . '/../extensions/phpqrcode/qrlib.php');

class SiteController extends Controller
{
    const MAX_NUMBER_OF_OFFERS = 10;

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

    /**
     * Displays the dashboard page
     */
    public function actionDashBoard()
    {
        $this->render('dashboard');
    }

    /**
     * Displays the offer editor page
     */
    public function actionOffers()
    {
        $this->render('stats');
    }

    /**
     * Displays the geolocation page
     */
    public function actionGeoLocation()
    {
        $this->render('geolocation');
    }

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
            // We can change this, so that it directs valid user to the business folder in the hosting cloud
            // echo "pass auth"; can use echo to debug.
			if($model->validate() && $model->login())
                //Yii::app()->user->setReturnUrl('site/dashboard');
               // $this->redirect(Yii::app()->user->returnUrl);
                $this->render('dashboard');

		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

    /**
     * Business Registration
     */
    public function actionRegistration() {
        // This is the correct registration order
        $business = new Business;
        $subscription = new Subscription;
        $account = new Account;

        //this variable is used in order to store new hash password
        $newUser = new Account;

        // ajax registration form validator
        if(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')
        {
            echo CActiveForm::validate($business, $subscription, $account);
            Yii::app()->end();
        }

        // collect user input data
        if(isset($_POST['Account'],$_POST['Business'], $_POST['Subscription'])) {

            //$business->attributes=((isset($_POST['Business'])?$_POST['Business']:array()));
            //$subscription->attributes=((isset($_POST['Subscription'])?$_POST['Subscription']:array()));
            $business->attributes=$_POST['Business'];
            $subscription->attributes=$_POST['Subscription'];
            $account->attributes=$_POST['Account'];

            // validate all three tables
            $valid=$business->validate();
            $valid=$subscription->validate() && $valid;
            $valid=$account->validate() && $valid;

            if($valid && $business->save()){
               $ph=new PasswordHash(Yii::app()->params['phpass']['iteration_count_log2'], Yii::app()->params['phpass']['portable_hashes']);
               $newUser->username = $account->username;
               $newUser->password = $ph->HashPassword($account->password);
               $newUser->email = $account->email;

               //account FK should have the correct value
               $newUser->business_id=$business->business_id;

               //subscription FK should have the correct value
               $subscription->business_id=$business->business_id;

               //save new business subscription
               $subscription->save();

               //save new user account and direct the business user to its new mobile web site
               if($newUser->save()) {
                  $identity=new UserIdentity($newUser->username,$account->password);
                  $identity->authenticate();
                  Yii::app()->user->login($identity,0);

                  // Desired folder structure, each business folder name should have 8 random charactors.
                  $length = 8;
                  $chars = array_merge( range('a', 'z'), range(0, 9));

                  shuffle($chars);
                  $folder = array_slice($chars, 0, $length);
                  //Yii::app()->getBasePath() or $_SERVER['DOCUMENT_ROOT'] to get site root
                  //getBasePath on linux: /var/www/html/business/protected
                  //getBasePath on Windows: C:\xampp\htdocs\business\protected
                   /* on Linux machine, path should be:
                   * $businessPath = realpath(Yii::app()->getBasePath().'/../..').'/'.implode('',$folder);
                   * on Windows machine, path should be:
                   * $businessPath = realpath(Yii::app()->getBasePath().'../../..').'/'.implode('',$folder);
                   */

                   if( strcasecmp(Yii::app()->params['HostOS'], "linux")==0){
                       $businessPath = realpath(Yii::app()->getBasePath().'/../..').'/'.implode('',$folder);
                   }else{
                       $businessPath = realpath(Yii::app()->getBasePath().'../../..').'/'.implode('',$folder);
                   }

                   // To create the business web folder
                   if (!mkdir($businessPath)) {
                      die('Failed to create folders...');
                   }
                   else{
                   //create this business mobile site folder by calling "yiic mbusiness <business_id + random 3 chars> "
                   $cmd=Yii::app()->getBasePath().'/'."yiic qrapp $businessPath $business->business_id";
                   exec($cmd);
                   print_r($cmd);
                   //create 10 dummy offers for this new business
                   for ($i=0; $i<self::MAX_NUMBER_OF_OFFERS; $i++){
                       $offer = new Offer;
                       // To make sure that this would add new record and not update
                       $offer->setIsNewRecord(true);
                       $offer->business_id=$business->business_id;
                       $offer->expiry_date = new CDbExpression('CURDATE()');
                       $offer->start_date = new CDbExpression('CURDATE()');
                       $offer->offer_detail = 'Please update this space with you new offer...';
                       $offer->save();
                   }

                   //create QR code for this business, then redirect the user to page he/she came from
                   $t=0;
                   $businessURL="http://".$_SERVER['SERVER_NAME'].'/'.implode('',$folder).'/'."index.php";

                   while( $t <=5 && !file_exists($businessPath.'/'."index.php")){
                       print_r("Creating the folder, please wait...");
                       print_r($businessURL);
                       sleep(10);
                       $t++;
                   }

                   //if folder was created successfully, then save this new QR URL
                   $business->home_url=$businessURL;
                   /*
                   //generate QR code by calling our primary QR code encoder - rest web serivce
                   //if access internet via proxy, then this will not work
                   $remoteQR_Server="http://api.qrserver.com/v1/create-qr-code/?data=[".$businessURL."]&size=[pixels]x[pixels]";

                   //test this url connection response
                   $file_headers = @get_headers($remoteQR_Server);

                   if(strpos($file_headers[0], '200') ===false) {

                   }
                   else {
                       Yii::trace("using second QR source...");
                       //Send a GET request of following form to our system to get a QR Code PNG-image:
                       $QR_Image=file_get_contents($remoteQR_Server);
                   }*/

                       //generate QR code by calling our local QR code encoder - qrlib.php on server
                       //set it to writable location, a place for temp generated PNG files
                       $errorCorrectionLevel='H';
                       $matrixPointSize=5;
                       $PNG_TEMP_DIR = dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'runtime'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;

                       //ofcourse we need rights to create temp dir
                       if (!file_exists($PNG_TEMP_DIR))
                           mkdir($PNG_TEMP_DIR);

                       $filename = $PNG_TEMP_DIR.'test'.md5($errorCorrectionLevel.'|'.$matrixPointSize).'.png';
                       //output information to runtime application log
                       Yii::trace("Temp directory and file name:".$filename."Dir:".$PNG_TEMP_DIR);

                       QRcode::png ($businessURL, $filename);
                       $QR_Image=file_get_contents($filename);

                   $business->qr_code=$QR_Image;
                   //imagepng(imagecreatefromstring($QR_Image));
                   //print_r($QR_Image);
                   //readfile($QR_Image);

                   $business->save(); //update the business qr image in database.

                   //redirect to new business page. $this->redirect('http://www.yiiframework.com');
                   //$this->redirect($businessURL);
                   $this->redirect(Yii::app()->homeUrl);
                   //yii app->end

                   }
                   /* send activation email
                   if (Yii::app()->controller->module->sendActivationMail) {
                      $activation_url = $this->createAbsoluteUrl('/user/activation/activation',array("activkey" => $model->activkey, "email" => $model->email));
                      UserModule::sendMail($model->email,UserModule::t("You registered from {site_name}",array('{site_name}'=>Yii::app()->name)),UserModule::t("Please activate you account go to {activation_url}",array('{activation_url}'=>$activation_url)));
                   }*/

               }
            }
        }

        // display the register form
        $this->render('registration',array('business'=>$business,'subscription'=>$subscription,'account'=>$account ));

    }

}